package com.facebook.app.client.uiElements;

import java.util.List;

import com.facebook.app.shared.clustering.Centroid;
import com.facebook.app.shared.clustering.Clusterable;
import com.facebook.app.shared.facebookData.FacebookFriend;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.TreeViewModel;

public class KMeansTreeModel implements TreeViewModel {
	
	private final SelectionModel<Clusterable> selectionModel;
	private final DefaultSelectionEventManager<Clusterable> selectionManager = DefaultSelectionEventManager.createCheckboxManager();
	private final Cell<Clusterable> cell;
	private final List<Centroid> centroids;
	
	public KMeansTreeModel(List<Centroid> centroids, SelectionModel<Clusterable> selectionModel, Cell<Clusterable> cell) {
		this.centroids = centroids;
		this.selectionModel = selectionModel;
		this.cell = cell;
	}

	@Override
	public <T> NodeInfo<?> getNodeInfo(T value) {

		if (value == null) {
			
			ListDataProvider<Centroid> dataProvider = new ListDataProvider<Centroid>(
					centroids);

			Cell<Centroid> centroidCell = new AbstractCell<Centroid>() {
				@Override
				public void render(Context context, Centroid value,
						SafeHtmlBuilder sb) {
				}
			};

			return new DefaultNodeInfo<Centroid>(dataProvider, centroidCell);
		} else if (value instanceof Centroid) {
			
			ListDataProvider<Clusterable> dataProvider = new ListDataProvider<Clusterable>(
					((Centroid) value).getClusterElements());
			
			return new DefaultNodeInfo<Clusterable>(dataProvider, cell, selectionModel, selectionManager, null);
		}
		
		throw new IllegalArgumentException("Unsupported object type: " + value.getClass().getName());
	}
	
	@Override
	public boolean isLeaf(Object value) {
		return value instanceof FacebookFriend;
	}

}
